package service;

import dao.StudentDao;
import entity.Student;
import entity.StudentCard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * StudentServiceImpl
 *
 * @description:
 * @Author XiaoZhou
 * @Date 2023/11/23 13:56
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    @Qualifier("studentDao")
    private StudentDao studentDao;

    @Autowired
    private PlatformTransactionManager transactionManager;

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
    @Transactional(rollbackFor=Exception.class)
    @Override
    public void addStudent(Student student) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            studentDao.addStudent(student);
            transactionManager.commit(status); // 提交事务
        } catch (Exception e) {
            transactionManager.rollback(status); // 回滚事务
        }
    }
    @Transactional(rollbackFor=Exception.class)
    @Override
    public void addStudentCard(StudentCard studentCard) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            // 新增学生证信息
            studentDao.addStudentCard(studentCard);

            transactionManager.commit(status); // 提交事务
        } catch (Exception e) {
            transactionManager.rollback(status); // 回滚事务
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void addStudentandCard(Student student,StudentCard studentCard){
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            studentDao.addStudent(student);

            int abc = student.getStu_id();
            StudentCard card = new StudentCard();
            card.setStu_id(abc);
            card.setClass_info(studentCard.getClass_info());
            card.setMajor(studentCard.getMajor());
            studentDao.addStudentCard(card);

            transactionManager.commit(status); // 提交事务

        } catch (Exception e) {
        transactionManager.rollback(status); // 回滚事务
    }
    }





}
